
var ground_request = {
    
    init: function() {
        
        var self = this;
        
        self.setupTabsAndGrids();
        self.setupSearchField();
        
        /**
         * Setup the flyout to close and show the scheduling setup UI
         */
        $("#add_new_request").data({
            'load-callback': function() {
                ground_request.setupRequestFields();
            },
            'callback': function(data) {
                $("#tabs").tabs('load', $("#tabs").tabs('option','selected'));
            
                core.showFlyout({
                    content: data,
                    load: Services.init,
                    close: function() {
                        $("#tabs").tabs('load', $("#tabs").tabs('option','selected'));
                    }
                });
            }
        });
        
        $("#ground_handling_form").submit(function(event){
            event.preventDefault();
            self.processForm();
        });

        $(".lk_open").click(function(){
            $(".buttons li").removeClass('active');
            $(".buttons li").attr('href','#');
            var $menu = $("#actions").find(".menu");
            $menu.hide();
        });


        $(".print_form").click(function(e){
            window.open($(this).attr("href"));
        });

        $("#actions").click(function(e) {
            e.preventDefault();
            var $menu = $(this).find(".menu");
            
            if($("#edit_req").attr("href")=="#"){
                $menu.hide();
                return;
            }
            
            else {
                if($menu.is(":visible")){
                    $menu.show().focus();
                } else {
                    $menu.hide();
                }
            }            
        });
    },
    
    setupTabsAndGrids: function() {
        
        $("#tabs").bind('tabsload', function(event, ui) {
            $("#gr_table .edit_link").data({
                "load-callback": function() {
                    ground_request.setupRequestFields();
                },
                'callback': function() {
                    ground_request.loadRequestDetails( $("#gr_table tbody tr.selected").attr('id') );
                }
            });
            
            
            $(ui.panel).find("#gr_table tbody tr:first").addClass('selected');
            ground_request.loadRequestDetails( $(ui.panel).find("tr.selected").attr('id') );
        });
        
        $("#gr_table tbody tr").live('click', function(e) {
            ground_request.loadRequestDetails( $(this).attr('id') );
        });
        
        $("#gr_table .del_req").live('click', function(e){
            e.preventDefault();
            e.stopPropagation();
            
            if( !confirm("You are about to CANCEL this request and all related Flight Schedules. Are you sure you want to proceed with the cancellations?")){
                return; 
            }
            
            var $self = $(this);
            
            $.ajax({
                type: 'get',
                url: $(this).attr("href"),
                data: {},
                dataType: 'json',
                success: function(data) {
                    if( data.error == 0 ) {
                        $self.parents("tr").remove();
                        $("#services_show").html("Select Request On The Left To View Details of Flight Schedules and Handlers Here");
                    }
                    
                    else {
                        humane.timeout = 2500;
                        humane.error( data.message );
                    }
                },
                error: function(xhr, text) {
                    console.log(xhr.responseText);
                    human.error("Failed To Close Request Successfully");
                }
            });
        });
        
        
    },  

    loadRequestDetails: function( ground_request_id ) {
        
        if( !ground_request_id ) {
            $("#services_show").html("");
            return;
        }
        
        //an ajax request will be made here which will populate
        var url_req = $("#service_list").val();
        var query="req_id=" + ground_request_id;
            
        $.ajax({
            url: url_req,
            data: query,
            type: "GET",
            dataType: 'html',
            success: function(data) {
                $("#services_show").html(data);
                
                /**
                 * Fix z-indexes to prevent Action Menu Overlap
                 */
                var zIndexFix = 10;
                $(".schedule").each(function() {
                    $(this).css('z-index', zIndexFix);
                    $(this).find('.menu_button').css('z-index', zIndexFix--);
                });
                
                $(".schedule .menu_button").click(function(e) {
                    e.preventDefault();
                    var $menu = $(this).find(".menu");

                    if($menu.is(":visible")){
                        $menu.hide();

                    } else {
                        $menu.show().focus();
                    }
                });
                
                if( $("#cancelled_perms").is(":visible") ) {
                    $(".schedule .menu .open_only").hide();
                    $(".schedule .menu .canceled_only").show();
                }
                
                else if( $("#closed_perms").is(":visible") ) {
                    $(".schedule .menu .open_only, .schedule .menu .canceled_only").hide();
                    $(".schedule .menu .closed_only").show();
                }
                
                else {
                    $(".schedule .menu .closed_only, .schedule .menu .canceled_only").hide();
                    $(".schedule .menu .open_only").show();
                }
                
                $(".schedule .menu_button .menu").blur(function() {
                    $(this).hide();
                });

                $(".schedule a.expander").click(function(e) {
                    e.preventDefault();
                        
                    $(this).toggleClass('expanded');
                    $(this).parents('.schedule').find(".services").slideToggle();
                    $(this).parents(".schedule").toggleClass("expanded");
                        
                    return false;
                });
                
                $(".schedule .services:first").show();
                $(".schedule:first, .schedule:first a.expander").toggleClass("expanded");
                
                $("#request_details #schedule_add_new, .schedule .edit_link").data({
                    'load-callback': Services.init,
                    'callback': function() {
                        ground_request.loadRequestDetails( $("#gr_table tbody tr.selected").attr('id') );
                    }
                });
                
                $(".schedule .delete_link").click(function(e) {
                    e.preventDefault();
                    
                    if( confirm('Are you sure you want to delete this schedule and the related services?\n\nNote: The schedule will be removed and the Reference Number used will not be available for re-use.')) {
                        var _this = this;
                        
                        $.get( $(_this).attr('href'), function() {
                            $(_this).closest("div.schedule").remove(); 
                        });
                    }
                });
                
                $(".schedule .cancel_link").click(function(e) {
                    e.preventDefault();
                    
                    if( confirm('You are about to cancel this schedule and move the request information to the Canceled Requests section.\nAre you sure you want to CANCEL this schedule?')) {
                        var _this = this;
                        
                        $.get( $(_this).attr('href'), function() {
                            if( $(".schedule").length == 1 ) {
                                $(_this).closest("div.schedule").remove(); 
                                $("#gr_table tbody tr.selected").remove(); 
                            }
                            
                            else {
                                $(_this).closest("div.schedule").addClass("cancelled");
                            }
                        });
                    }
                });
                
                $(".schedule #re-open").click(function(e) {
                    e.preventDefault();
                    
                    if( confirm('You are about to Re-instate this schedule and move the request information to the Open Requests section.\nAre you sure you want to RE-INSTATE this schedule?')) {
                        var _this = this;
                        
                        $.get( $(_this).attr('href'), function() {
                            if( $(".schedule").length == 1 ) {
                                $(_this).closest("div.schedule").remove(); 
                                $("#gr_table tbody tr.selected").remove(); 
                            }
                            
                            else {
                                $(_this).closest("div.schedule").addClass("cancelled");
                            }
                        });
                    }
                });
                
                $("#update_actuals.flyout_opener").data({
                    'callback': function() {
                        ground_request.loadRequestDetails( $("#gr_table tbody tr.selected").attr('id') );
                    }
                });
                
                $("#send_handler.flyout_opener").data('load-callback', function() {
                    //$("#handler_id").chosen();
                    try {
                        tinyMCE.init({
                            mode : "textareas",
                            theme : "advanced",
                            plugins : "advimage",
                            theme_advanced_toolbar_location : "top",
                            theme_advanced_toolbar_align : "left",
			
                            theme_advanced_resizing : true,
			
                            // Theme options
                            theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink", //,image,code
                            theme_advanced_buttons2 : ""
                        });
                    } catch(e) {
                        console.log(e);
                    }
                    
                });
            },
            error: function(xhr) {
                humane.error("Failed To Load Request Details");
                
                console.log(xhr);
            }
        });
    },
    
    setupSearchField: function() {
        $("#search_term").change(function() {
            var option = this.options[this.selectedIndex];
             
            $("#schedule-search").attr("placeholder", $(option).data('placeholder'));
        }).css({
            'font-size': '11px'
        });
        
        var searchForSchedule = function () {
            var query = "term=" + $("#schedule-search").val()+"&filter="+$("#search_term").val();
            var url = $("#schedule-search").data('url');
                     
            $.ajax({
                url: url,
                data: query,
                //dataType: 'json',
                type: 'post',
                success: function(data) {
                    var panel = $(".ui-tabs-panel").get( $("#tabs").tabs('option','selected') );
                    $(panel).html(data);
                    
                    $(panel).find("#gr_table tbody tr:first").addClass('selected');
                    ground_request.loadRequestDetails( $(panel).find("#gr_table tbody tr.selected").attr('id') ); 
                },
                error: function(xhr) {
                    console.log(xhr.responseText);
                }
            });
        };
        
        $("#schedule-search").keyup(function(e) {
            if( e.keyCode == 13 ) {
                searchForSchedule();
            }
        });
    },
    
    setupRequestFields: function() {
        $("#mtow_kgs").keyup(function() {
            var kgs = parseInt($(this).val().toLowerCase().replace('kgs', ''));
            var lbs = kgs * 2.2;
                
            $("#mtow_lbs").html( (lbs ? lbs.toFixed(0) : 0) + " LBS" );
        });
                
        $("#card_expiry_dt").datepicker({ 
            showButtonPanel: false,
            showOn: "both",
            buttonImage: "../../img/core/ico-12.png",
            buttonImageOnly: true,
            minDate: -30,
            changeMonth: true,
            changeYear: true,
            dateFormat: 'yy-mm-dd',
            timeFormat: 'hh:mm'
        });
    }
};

$(document).ready(function(){
    ground_request.init();
});
